<template>
  <view class="blood_oxygen">
    <!-- 血氧 -->
    <view class="card blood" :class="{ noDay: selectType !== 'day' }">
      <view class="head">
        <view class="title">
          <view class="title-text">
            <view class="title-content"> 血氧 </view>
            <TagState></TagState>
          </view>
          <uni-icons
            type="info"
            class="info-icon"
            size="20"
            color="#666666"
          ></uni-icons>
        </view>
      </view>
      <view class="value">
        <text style="font-size: 30px">{{ blood.min }}-{{ blood.max }}</text>
        <text style="font-size: 14px; color: #999999">%</text>
        <br />
        <text style="font-size: 14px; color: #999999"
          >推荐值：{{
            blood.allData.bloodOxModel
              ? blood.allData.bloodOxModel.config.min
              : 0
          }}-{{
            blood.allData.bloodOxModel
              ? blood.allData.bloodOxModel.config.max
              : 0
          }}%</text
        >
      </view>
      <view class="chart">
        <!-- <view v-if="notDataOrLoading" class="noData_loading_mask">
          {{ !blood.loading ? "暂无数据" : "加载中..." }}
        </view> -->
        <l-echart ref="chartRef"></l-echart>
      </view>
      <view
        style="
          height: 40px;
          background-color: #dceefd;
          color: #7cb5ff;
          font-size: 14px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 0 10px;
          border-radius: 10px;
        "
      >
        <text>最新：{{ bloodOxygenTime }}</text
        ><text>{{ bloodOxygen }} %</text>
      </view>
    </view>
  </view>
</template>

<script>
import dayjs from "dayjs";
import * as echarts from "echarts";
import { getBloodData } from "@/api/ring/report.js";
import TagState from "@/components/tag-state/index.vue";

import bImage from "@/static/ring/chart/blood.png";

import {
  queryMyBloodOxInfoByDay,
  queryMyBloodOxInfoByWeek,
  queryMyBloodOxInfoByMonth,
} from "@/api/ring/chart.js";

const tip_zh = `
血氧饱和度（SpO2）表示血液中氧气的饱和程度，通常在95%-100%之间。少数健康个体可能低于95%，但若血氧饱和度低于90%请注意观察，必要请及时就医。

请在静息状态下将设备的传感器凸点紧贴指腹，以确保准确读数。

*运动或在身处高原地区时，血氧浓度数据可能与实际有一定偏差。

注：本设备提供的检测数据仅用于日常健康管理辅助参考，不可替代专业医疗诊断。
`;

const _options = {
  // 浅蓝渐变背景（通过grid实现）
  grid: {
    top: 40,
    right: 30,
    bottom: 30,
    left: 20,
    backgroundColor: {
      type: "linear",
      x: 0,
      y: 0,
      x2: 0,
      y2: 1,
      colorStops: [
        { offset: 0, color: "rgba(200, 220, 255, 0.8)" }, // 顶部浅蓝
        { offset: 1, color: "rgba(230, 240, 255, 0.3)" }, // 底部更浅
      ],
    },
  },
  // 横轴（时间轴）
  xAxis: {
    type: "category",
    data: [
      "0:00",
      "1:00",
      "2:00",
      "3:00",
      "4:00",
      "5:00",
      "6:00",
      "7:00",
      "8:00",
      "9:00",
      "10:00",
      "11:00",
    ],
    axisLine: { lineStyle: { color: "#999" } },
    axisTick: {
      show: false,
    },
  },
  // 纵轴（数值轴）
  yAxis: {
    type: "value",
    min: 0,
    interval: 100,
    position: 'right',
    max: 200,
    axisLabel: {
      formatter: "{value}",
      color: "#666",
    },
    splitLine: { lineStyle: { color: "rgba(150, 150, 150, 0.1)" } }, // 浅色分割线
  },
  // 折线数据系列
  series: [],
};

export default {
  props: {
    selectDateInfo: Object,
  },
  components: {
    TagState,
  },
  data() {
    return {
      selectType: "day",
      bloodOxygen: 0,
      bloodOxygenTime: "",
      blood: {
        showTip: false,
        tipText: tip_zh,
        max: 0,
        min: 0,
        averageNum: 0,
        chartData: [],
        chartRef: null,
        chart: null,
        healthText: "",
        healthModelValue: 0,
        loading: false,
        empty: false,
        allData: {
          bloodOxModel: {
            config: {
              min: 0,
              max: 0,
            },
          },
        },
      },
    };
  },

  computed: {
    notDataOrLoading() {
      const data = this.blood.chartData;
      return !data || !Array.isArray(data) || !data.length;
    },

    optionsByDay() {
      return {
        ..._options,
        series: [
          {
            type: "line",
            barWidth: 6,
            itemStyle: {
              opacity: 1,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgba(247, 61, 61, 1)",
                },
                {
                  offset: 1,
                  color: "rgba(244, 103, 103, 0.3)",
                },
              ]),
              borderRadius: 10,
            },
            data: this.blood.chartData,
          },
        ],
      };
    },
    optionsByOther() {
      return {
        ..._options,
        series: [
          {
            name: "血氧",
            type: "line",
            smooth: false,
            lineStyle: {
              width: 1.5,
              color: "#E7F4FD",
            },
            areaStyle: {
              opacity: 0,
            },
            showSymbol: true,
            symbol: "circle",
            itemStyle: {
              color: "#7CB5FF",
            },
            data: this.blood.chartData,
          },
        ],
      };
    },
  },

  watch: {
    selectDateInfo: {
      handler(nv) {
        const param = {
          type: "day",
          startTime: nv.fulldate,
        };
        this.chooseDate = dayjs(nv.fulldate).format("MM月DD日");
        this.bloodOxygenOnChange(param);
        this.updateBloodData(nv.fulldate);
      },
      immediately: true,
      deep: true,
    },

    optionsByDay: {
      handler(nv) {
        if (this.selectType === "day") {
          if (this.blood.chart) {
            this.blood.chart.setOption(nv);
          }
        }
      },
      deep: true,
    },

    optionsByOther: {
      handler(nv) {
        if (this.selectType !== "day") {
          if (this.blood.chart) {
            this.blood.chart.setOption(nv);
          }
        }
      },
      deep: true,
    },
  },

  async mounted() {
    if (!this.blood.chartRef) {
      this.blood.chartRef = this.$refs.chartRef;
    }
    if (this.blood.chartRef) {
      this.blood.chart = await this.blood.chartRef.init(echarts);
    }
    let currentDate = dayjs().format("YYYY-MM-DD");
    if (this.selectDateInfo.fulldate) {
      currentDate = this.selectDateInfo.fulldate;
    }
    this.chooseDate = dayjs(currentDate).format("MM月DD日");
    const param = {
      type: "day",
      startTime: currentDate,
    };
    await this.bloodOxygenOnChange(param);
    await this.updateBloodData(currentDate);
  },

  methods: {
    updateBloodData(date) {
      let dateFormat = dayjs(date).format("YYYYMMDD");
      getBloodData({
        dateFormat: dateFormat,
        offsetMinutes: new Date().getTimezoneOffset(),
      })
        .then((res) => {
          if (res.data) {
            this.bloodOxygen = res.data.value;
            this.bloodOxygenTime = dayjs(res.data.dateTimeFormat).format(
              "HH:mm"
            );
          } else {
            this.bloodOxygen = "";
            this.bloodOxygenTime = "";
          }
        })
        .catch((error) => console.log(error));
    },
    async bloodOxygenOnChange(data) {
      this.blood.chart.setOption({
        ..._options,
        series: [
          {
            type: "line",
            data: [95, 102, 88, 110, 98, 105, 120, 164,121,97,95, 102, 88, 110], // 示例数据（峰值164在7:00）
            symbol: "none", // 默认不显示数据点
            lineStyle: {
              color: "#cccccc", // 主折线颜色
              width: 2,
            },
            // 标记峰值点（红色圆点）
            markPoint: {
              symbol: "circle",
              symbolSize: 8,
              itemStyle: { color: "#7cb5ff" }, // 红色
              label: { show: true },
              data: [
                {
                  name: "峰值",
                  coord: ["7:00", 164], // 对应峰值位置
                },
              ],
            },
          },
        ],
      });
      return;
      const { type, startTime, endTime } = data;
      this.blood.max = 0;
      this.blood.min = 0;
      this.blood.averageNum = 0;
      this.blood.healthText = "";
      this.blood.healthModelValue = 0;
      this.blood.chartData = [];
      this.blood.loading = true;
      this.resetData();

      const offsetMinutes = new Date().getTimezoneOffset();

      const params =
        type == "day"
          ? { dateStr: startTime, offsetMinutes }
          : type === "week"
          ? { dateBeginStr: startTime, dateEndStr: endTime, offsetMinutes }
          : { dateBeginStr: startTime, dateEndStr: endTime, offsetMinutes };
      console.log("params", params);

      const requestMethod =
        type == "day"
          ? queryMyBloodOxInfoByDay
          : type == "week"
          ? queryMyBloodOxInfoByWeek
          : queryMyBloodOxInfoByMonth;

      try {
        const { data } = await requestMethod(params);

        this.blood.loading = false;

        console.log("bloodOxygenOnChange", data);
        if (this.blood.chart) {
          this.blood.chart.clear();
        }
        if (!data) {
          this.resetData();
          return;
        }
        this.blood.allData = data;
        this.blood.max = parseInt(data.max || 0);
        this.blood.min = parseInt(data.min || 0);
        this.blood.averageNum = parseInt(data.average || 0);
        this.blood.healthText = data?.bloodOxModel?.config?.modelZh;
        this.blood.healthModelValue = parseInt(data?.bloodOxModel?.value || 0);
        if (!data.rates) return;
        const dealWith =
          type == "day" ? this.bloodGetFullByDay : this.bloodGetFullByOther;
        dealWith(data.rates || []);
      } catch (error) {
        console.log("heartRateOnChange error", error);
        this.resetData();
      } finally {
        this.blood.loading = false;
      }
    },

    bloodGetFullByDay(data) {
      let res = [];
      for (let i = 0; i < 24; i++) {
        const has = data.findIndex((item) => Number(item.time) === i);
        if (has != -1) {
          res.push([i.toString() + ":00", data[i].value || null]);
        } else {
          res.push([i.toString() + ":00", null]);
        }
      }
      res.sort((a, b) => Number(a[0]) - Number(b[0]));
      this.blood.chartData = res;
    },

    bloodGetFullByOther(data) {
      const cycleCount = this.selectType == "week" ? 7 : data.length;
      let res = [];
      for (let i = 0; i < cycleCount; i++) {
        res.push([dayjs(data[i].date).format("MM.DD"), data[i].value || null]);
      }
      this.blood.chartData = res;
    },

    async resetData() {
      this.blood.chartData = [];
      this.blood.averageNum = 0;
    },

    openTip() {
      const tips = {
        tip: tip_zh,
        icon: bImage,
        title: "血氧",
      };

      this.$emit("tips", tips);
    },
  },
};
</script>

<style lang="scss" scoped>
.blood_oxygen {
  width: 100%;
  height: max-content;

  .w-92rpx {
    width: 92rpx;
  }

  .w-60rpx {
    width: 60rpx;
  }

  .w-70rpx {
    width: 70rpx;
  }

  .w-40rpx {
    width: 40rpx;
  }

  .w-30rpx {
    width: 30rpx;
  }

  .mr-8rpx {
    margin-right: 8rpx;
  }

  .text-#AFAFAF {
    color: #afafaf;
  }

  .card {
    width: 100%;

    background-color: rgba($color: white, $alpha: 0.4);
    backdrop-filter: blur(20rpx);
    border-radius: 8px;
    height: 740rpx;

    padding: 40rpx;

    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .head {
      width: 100%;
      height: 70rpx;
      display: flex;
      align-items: center;
      justify-content: flex-start;

      .title {
        width: 100%;
        font-size: 32rpx;
        font-weight: 600;
        text-align: left;
        margin-right: 12rpx;
        display: flex;
        justify-content: space-between;
      }

      .value {
        margin-left: auto;
        font-weight: 500;
        font-size: 64rpx;

        text {
          font-size: 24rpx;
        }
      }
    }

    .chart {
      width: 100%;
      height: 400rpx;
      position: relative;

      .noData_loading_mask {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: #e3f1fb;
        display: flex;
        justify-content: center;
        align-items: center;
        text-align: center;
        line-height: 150px;
        font-size: 28rpx;
        color: rgba(45, 153, 255, 1);
      }
      // background-color: #e5404f;
    }

    .range {
      display: flex;
      padding: 20rpx 52rpx 0 40rpx;
      font-weight: 500;

      .des {
        flex: 1;
        color: black;
        font-size: 32rpx;

        .desTop {
          display: flex;
          align-items: center;
          margin-bottom: 4rpx;
          white-space: nowrap;

          .titleTime {
            font-size: 28rpx;
            color: black;
            margin-left: 20rpx;
          }

          .dot {
            background: #e5404f;
            border-radius: 50%;
            width: 10rpx;
            height: 10rpx;
          }
        }

        .value {
          padding-left: 30rpx;

          .unit {
            font-size: 24rpx;
            margin-left: 8rpx;
          }
        }
      }
    }

    & + .card {
      margin-top: 40rpx;
      height: 730rpx;
    }

    &.noDay.blood {
      height: 640rpx;
    }
  }

  .info {
    color: black;
    padding: 40rpx;

    .info-title {
      height: 60rpx;
      display: flex;
      align-items: center;
      font-family: PingFang HK;
      font-size: 36rpx;
      font-weight: 600;
      line-height: 50px;
      text-align: left;
      padding: 40rpx 0;

      .value {
        margin-left: auto;
      }
    }

    .info-content {
      font-family: PingFang SC;
      font-size: 28rpx;
      font-weight: 300;
      line-height: 40rpx;
      text-align: left;
    }
  }
}

.info-icon {
  font-weight: 500;
  color: rgba(0, 0, 0, 0.2) !important;
}
.title-text {
  display: flex;
  align-items: center;
  .title-content {
    margin-right: 8px;
  }
}
</style>
